package main

import (
	"errors"
	"fmt"
	"github.com/nfnt/resize"
	"github.com/rwcarlsen/goexif/exif"
	"image"
	"image/jpeg"
	"os"
)

var (
	OrientationDecodeError     = errors.New("failed to decode file, err")
	OrientationError           = errors.New("failed to get orientation")
	OrientaionConvertTypeError = errors.New("failed to convert type of orientation")
)

//方向判断
func ReadOrientation(filename string) (int, error) {
	file, err := os.Open(filename)
	if err != nil {
		return 0, err
	}
	defer file.Close()

	x, err := exif.Decode(file)
	if err != nil {
		return 0, OrientationDecodeError
	}
	orientation, err := x.Get(exif.Orientation)
	if err != nil {
		return 0, OrientationError
	}
	orientVal, err := orientation.Int(0)
	if err != nil {
		return 0, OrientaionConvertTypeError
	}
	fmt.Println("the value of photo orientation is :", orientVal)
	return orientVal, nil
}

//旋转90度
func rotate90(m image.Image) image.Image {
	rotate90 := image.NewRGBA(image.Rect(0, 0, m.Bounds().Dy(), m.Bounds().Dx()))
	//矩阵旋转
	for x := m.Bounds().Min.Y; x < m.Bounds().Max.Y; x++ {
		for y := m.Bounds().Max.X - 1; y >= m.Bounds().Min.X; y-- {
			//设置像素点
			rotate90.Set(m.Bounds().Max.Y-x, y, m.At(y, x))
		}
	}
	return rotate90
}

// 旋转180度
func rotate180(m image.Image) image.Image {
	rotate180 := image.NewRGBA(image.Rect(0, 0, m.Bounds().Dx(), m.Bounds().Dy()))
	// 矩阵旋转
	for x := m.Bounds().Min.X; x < m.Bounds().Max.X; x++ {
		for y := m.Bounds().Min.Y; y < m.Bounds().Max.Y; y++ {
			//  设置像素点
			rotate180.Set(m.Bounds().Max.X-x, m.Bounds().Max.Y-y, m.At(x, y))
		}
	}
	return rotate180
}

// 旋转270度
func rotate270(m image.Image) image.Image {
	rotate270 := image.NewRGBA(image.Rect(0, 0, m.Bounds().Dy(), m.Bounds().Dx()))
	// 矩阵旋转
	for x := m.Bounds().Min.Y; x < m.Bounds().Max.Y; x++ {
		for y := m.Bounds().Max.X - 1; y >= m.Bounds().Min.X; y-- {
			// 设置像素点
			rotate270.Set(x, m.Bounds().Max.X-y, m.At(y, x))
		}
	}
	return rotate270
}
func MakeThumbnail(imagePath, savePath string) error {
	ori, err := ReadOrientation(imagePath)
	if err != nil {
		return err
	}
	file, _ := os.Open(imagePath)
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		return err
	}
	//苹果手机拍照的图片，会有方向属性Orientation，
	//经过Decode和Encode，编码处理后，方向属性会丢失，导致图片被旋转
	switch ori {
	case 6: //90度图片旋转
		img = rotate90(img)
	case 3:
		img = rotate180(img)
	case 8:
		img = rotate270(img)
	}
	w := 900
	h := 1200
	//调用resize库 进行图片压缩
	m := resize.Resize(uint(w), uint(h), img, resize.Lanczos3)
	//需要保存的文件
	imgfile, _ := os.Create(savePath)
	defer imgfile.Close()
	//以 jpeg 格式保存文件
	err = jpeg.Encode(imgfile, m, &jpeg.Options{70})
	if err != nil {
		return err
	}
	return nil
}

//https://blog.csdn.net/qq_33878858/article/details/103633565
func main() {
	//1.0
	//ori,_:=ReadOrientation("3.png")
	//fmt.Println(ori)
	//err:=MakeThumbnail("2.jpg","2.png")
	//if err != nil{
	//	fmt.Println(err.Error())
	//}
	ori, _ := ReadOrientation("2.jpg")
	fmt.Println(ori)
}
